package com.pet_clinic.controller;


import com.atguigu.campus.pojo.Admin;
import com.atguigu.campus.service.AdminService;
import com.atguigu.campus.utils.Result;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.core.util.StrUtil;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.HandlerMapping;

import java.util.List;

@RestController
@RequestMapping("/sms/adminController")
public class AdminController {

    @Resource
    private AdminService adminService;
    @Autowired
    private HandlerMapping resourceHandlerMapping;

    /**
     * 带条件的分页查询功能
     * @param pn 当前页码
     * @param pageSize 每页显示的记录数
     * @param adminName 模糊查询条件
     * @return 返回查询结果封装page对象
     */
    @GetMapping("/getAllAdmin/{pn}/{pageSize}")
    public Result<Object> getadmin(@PathVariable("pn")Integer pn, @PathVariable("pageSize")Integer pageSize,String adminName){

        Page<Admin> page = adminService.page(new Page<>(pn, pageSize), new LambdaQueryWrapper<Admin>().like(StrUtil.isNotBlank(adminName), Admin::getName, adminName).orderByDesc(Admin::getId));

        return Result.ok(page);
    }


    /**
     *单条记录和批量删除功能
     * @param idlist 请求体中待删除的年纪id的集合（List）
     * @return
     */
    @DeleteMapping("/deleteAdmin")
    public Result<Object> deleteadmin(@RequestBody List<Integer> idlist){

        //单条记录删除
        if(idlist.size()==1){
            adminService.removeById(idlist.get(0));
        }else {
            adminService.removeByIds(idlist);
        }
        return Result.ok();
    }

    /**
     * 根据判断请求体中是否存在id 进行判断是添加还是修改
     * @param admin 把请求体中的JSON数据封装到实体类Grade中
     * @return 返回成功
     */
    @PostMapping("/saveOrUpdateAdmin")
    public Result<Object> saveOrUpdateGrade(@RequestBody Admin admin){

        //判断请求体中是否存在id，存在是修改，否则是添加
        Integer id = admin.getId();
        if(id!=null){
            adminService.update(admin,new LambdaQueryWrapper<Admin>().eq(Admin::getId,id));
        }else {
            adminService.save(admin);
        }
        return Result.ok();
    }
}
